<template>
  <span>
    <el-checkbox v-if="isAllShow" v-model="checkAll" :indeterminate="isIndeterminate" @change="handleCheckAllChange">全选</el-checkbox>
    <el-checkbox-group v-if="isGroup" v-model="groupValue" v-bind="$attrs" v-on="$listeners" @change="change">
      <el-checkbox v-for="v of options" :key="v.value || v.label || v" :label="v.label || v">{{ v.label || v }}</el-checkbox>
    </el-checkbox-group>
    <el-checkbox v-else :value="value" v-bind="$attrs" @change="change" v-on="$listeners">
      <slot />
    </el-checkbox>
  </span>
</template>

<script>
export default {
  name: 'MyCheckbox',
  model: { prop: 'value', event: 'change' },
  props: {
    isGroup: { type: Boolean, default: false },
    value: { type: [String, Number, Boolean, Array], default: '' },
    needAllCheck: { type: Boolean, default: false },
    options: { type: Array, default: () => [] }
  },
  data() {
    return {
      checkAll: false,
      isIndeterminate: false,
      groupValue: []
    }
  },
  computed: {
    isAllShow() {
      return this.isGroup && this.needAllCheck
    }
  },
  watch: {
    'value': {
      handler: function(val) {
        if (this.isGroup) {
          if (!Array.isArray(val)) {
            throw new Error("when use prop of 'isGroup', the prop of 'value' must is type Array")
          }
          this.groupValue = this.value
        }
      },
      immediate: true
    }
  },
  methods: {
    change(val) {
      if (this.isAllShow) {
        const checkedCount = val.length
        this.checkAll = checkedCount === this.options.length
        this.isIndeterminate = checkedCount > 0 && this.options.length > checkedCount
      }
      this.$emit('change', val)
    },
    handleCheckAllChange(val) {
      if (!this.isAllShow) return
      this.change(val ? this.options : [])
    }
  }
}
</script>

<style>

</style>
